<?php

class Application_Model_LevelMapper {
    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Level');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Level $Level) {
        $data = array(
            'level'   => $Level->getLevel(),
            'name' => $Level->getName(),
        );

        if (null === ($id = $Level->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function delete(Application_Model_Level $Level) {
        $data = array(
            'level'   => $Level->getLevel(),
            'name' => $Level->getName(),
            'id' => $Level->getId(),
        );

        $id = $Level->getId();

        $this->getDbTable()->delete(array('id = ?' => $id));
    }

    public function find($id, Application_Model_Level $Level) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $Level->setId($row->id)
            ->setLevel($row->level)
            ->setName($row->name);
    }

    public function fetchByLevel($level) {

        $table = new Application_Model_DbTable_Level();
        $select = $table->select();
        $select->from($table)->where('level = ?', $level);

        $resultSet = $table->fetchAll($select);

        //$resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Level();

            $result = $this->getDbTable()->find($row->id);

            if (count($result) > 0) {
                $q = $result->current();
                $entry->setId($q->id)
                    ->setName($q->name)
                    ->setLevel($q->level);
                $entries[] = $entry;
            }
        }

        if (count($entries)>0) {
            return $entries[0];
        } else {
            return null;
        }
    }
    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll(null, 'level asc');
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Level();
            $entry->setId($row->id)
                ->setLevel($row->level)
                ->setName($row->name);
            $entries[] = $entry;
        }
        return $entries;
    }

}

